package com.example.demo.filter;


import org.apache.commons.io.IOUtils;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ParamsWrapper extends HttpServletRequestWrapper {

    private static Map<String, String[]> parameterMap = new HashMap<>();
    HttpServletRequest request;

    public ParamsWrapper(HttpServletRequest request) {
        super(request);

        //对 request.getParameterMap() 进行操作
        parameterMap.putAll(request.getParameterMap());
        this.request = request;
    }

    /**
     * 对于请求参数是K=V格式的通过HttpServletRequest.getParameterMap就可以直接获取。
     * 但是对于JSON格式的参数，我们需要从request的inputStream中读取。
     */
    @Override
    public ServletInputStream getInputStream() throws IOException {

        ServletInputStream inputStream = super.getInputStream();
        //获取JSON字符串
        String s = IOUtils.toString(inputStream, "UTF-8");
        //操作

        //返回:由于流读取完后就消失了，需要再将流写出去
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(s.getBytes("UTF-8"));
        return new RequestCachingInputStream(byteArrayInputStream);
    }

    @Override
    public String[] getParameterValues(String name) {
        if ("param".equalsIgnoreCase(name)) {
            String[] results = parameterMap.get(name);
            results[0] = "bbbb";
            return results;
        }
        return parameterMap.get(name);
    }


}
